package com.thinkingcoder.tccache.core.operator;

import java.util.Arrays;

import com.thinkingcoder.tccache.core.model.CacheEntry;

/**
 * String operator.
 */
public class StringOperator extends AbstractOperator {
    public void set(String key, String value) {
        putCacheEntry(key, new CacheEntry<>(value, System.currentTimeMillis(), -1000L));
    }

    public String get(String key) {
        if (checkInvalid(key)) {
            return null;
        }

        return getStringEntryValue(key);
    }

    public String[] mGet(String... keys) {
        return keys == null ? new String[0] : Arrays.stream(keys).map(this::get).toArray(String[]::new);
    }

    public void mSet(String[] keys, String[] vals) {
        if (keys == null || keys.length == 0) {
            return;
        }

        for (int i = 0; i < keys.length; i++) {
            set(keys[i], vals[i]);
        }
    }

    public int incr(String key) {
        String strVal = get(key);
        int val = 0;
        try {
            if (strVal != null) {
                val = Integer.parseInt(strVal);
            }
            val++;
            set(key, String.valueOf(val));
        } catch (NumberFormatException e) {
            throw e;
        }
        return val;
    }

    public int decr(String key) {
        String strVal = get(key);
        int val = 0;
        try {
            if (strVal != null) {
                val = Integer.parseInt(strVal);
            }
            val--;
            set(key, String.valueOf(val));
        } catch (NumberFormatException e) {
            throw e;
        }
        return val;
    }

    public Integer strLen(String key) {
        if (checkInvalid(key)) {
            return 0;
        }
        return get(key) == null ? null : get(key).length();
    }

    private String getStringEntryValue(String key) {
        return (String)getCacheEntryValue(key);
    }
}
